<?php

namespace backend\grid;

use backend\assets\plugins\BootstrapAsset;
use Closure;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;

class InputColumn extends DataColumn
{
    public $ModelClass;
    public $Controller = 'upinput';
    public $Action     = 'update';
    public $reload     = '0';
    public $Type       = 'text';
    public $Options    = array();
    public $Url;
    public $Field;

    /**
     * {@inheritdoc}
     */
    protected function renderDataCellContent($model, $key, $index)
    {
        $this->registerClientScript();
        $type        = $this->getDataCellType($model, $key, $index);
        $thisOptions = $this->getDataCellOptions($model, $key, $index);
        $name        = 'score[]';
        $value       = $this->getDataCellValue($model, $key, $index);
        $Options     = [
//            'id' => $this->getInputid($model, $key),
            'data-inputid' => $this->getInputid($model, $key),
            'data-pjax'    => true,
            'data-reload'  => $this->reload,
        ];

        $Options     = empty($thisOptions) ? $Options : ArrayHelper::merge($Options, $thisOptions);
        $data_action = ArrayHelper::getValue($Options, 'data-action');
        $data_id     = ArrayHelper::getValue($Options, 'data-id');
        !empty($data_id) ?: $data_id = $key;

        $Options['data-url']        = $this->getUrl($model, $data_action, $data_id);
        $Options['data-field']      = $this->Field;
        $Options['data-modelclass'] = end(explode('\\', $this->ModelClass));
        $Options['data-params']     = [
            'modelClass'                          => $this->ModelClass,
            end(explode('\\', $this->ModelClass)) => ArrayHelper::merge(
                $Options['data-params'],
                [
                    'id'         => $model->id,
                    $this->Field => $value,
                ]
            ),
        ];
        $result                     = Html::input($type, $name, $value, $Options);

        return $result;
    }

    public function registerClientScript()
    {
        BootstrapAsset::register($this->grid->view);
        $JS = <<< JS
            $('.js-input').on('change', function(e){
                var input=$(this);
                var id =  input.data("id");
                var url =  input.data("url");
                var reload =  input.data("reload");
                var params = input.data("params");
                var field=input.data("field");
                var oldval=input.data(field);
                var modelclass=input.data("modelclass");
                var value=input.val();
                params[modelclass][field]=value;
                // alert(params[modelclass][field]);
                $.ajax({
                    "url": url,
                    "data":params,
                    "dataType": "json",
                    "type": 'post',
                    'beforeSend': function () {
                        layer.load(2, {
                            shade: [0.1, '#fff'] //0.1透明度的白色背景
                        });
                    },
                    "success": function (data) {
                        layer.msg(data.message,{time:400});
                        // setSwitchery(switchery,data.status);

                        if(input.data("action")=='create'){
                            input.data("action",'update');
                            input.data("id",data.model['id']);
                            var Url=url.replace('create', 'update').replace(/(id\=)\d/ ,'id='+data.model['id']);
                            input.data("url",Url);
                        }
                        if(reload){
                            location.reload();
                        }else{
                            input.val(data.model[field]);
                            $(input).parent().addClass('bg-success').removeClass('bg-warning');
                            // console.log(data);
                        }
                    },
                    "error": function (jqXHR, textStatus, errorThrown) {
                        input.val(params.score);
                        $(input).parent().addClass('bg-warning').removeClass('bg-success');
                        layer.msg('sorry!出现错误！请检查网络或者联系管理员！',{time:1000});
                       // alert(jqXHR.responseJSON.message);
                    },
                    "complete": function () {
                        layer.closeAll('loading');
                    }
                });
            });
JS;
        $this->grid->view->registerJs($JS, View::POS_READY); //因为可能会被pjax加载所以放在这里
    }

    public function getDataCellType($model, $key, $index)
    {
        if ($this->Type instanceof Closure) {
            return call_user_func($this->Type, $model, $key, $index, $this);
        } else {
            return $this->Type;
        }
    }

    public function getDataCellOptions($model, $key, $index)
    {
        if ($this->Options instanceof Closure) {
            return call_user_func($this->Options, $model, $key, $index, $this);
        } else {
            return $this->Options;
        }
    }

    public function getInputid($Model, $id)
    {
        $inputid = 'input_'.$id;

        return $inputid;
    }

    private function getUrl($Model, $action, $id)
    {
        //根据当前类名获取Controller
        if (empty($this->Url)) {
            //获取当前类名去掉命名空间名称
            $this->ModelClass = empty($this->ModelClass) ? end(explode('\\', $Model->className())) : $this->ModelClass;
            //根据当前类名获取Controller
            $this->Controller = empty($this->Controller) ? strtolower($this->ModelClass) : $this->Controller;
            $Controller       = (empty($this->Controller)) ? strtolower(end(explode('\\', $Model->className()))) : $this->Controller;
            if (empty($action)) {
                $action = $this->Action;
            }
            $Url = Url::to(['/'.$Controller.'/'.$action, 'id' => $id]);

            return $Url;
        }

        return $this->Url;
    }
}
